package com.tyc.shiro.config;

import com.tyc.shiro.oauth2.OAuth2Filter;
import com.tyc.shiro.oauth2.OAuth2Realm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2023-12-21 15:05:08
 */
@Configuration
public class ShiroConfig {

    @Bean("securityManager")
    public SecurityManager securityManager(OAuth2Realm oAuth2Realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(oAuth2Realm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        /*
        配合Shiro的内置过滤器,参见DefaultFilter
           anon : 无需认证就可以访问
           authc : 必须认证才可以访问 对应@RequiresAuthentication注解
           user : 用户登录且记住我 才可以访问 对应@RequiresUser注解
           perms : 拥有某个资源才可以访问 对应@RequiresPermissions注解
           roles : 拥有某个角色才可以访问  对应@RequiresRoles注解
         */
        //将自定义的 OAuth2Filter 放入 shiroFilter 并起名为 oauth2
        Map<String, Filter> filters = new HashMap<>(4);
        filters.put("oauth2", new OAuth2Filter());
        shiroFilter.setFilters(filters);
        Map<String, String> filterMap = new LinkedHashMap<>(8);
        // 配置不需要身份验证的资源
        filterMap.put("/sys/login", "anon");
        filterMap.put("/sys/captcha", "anon");
        // 配置需要名为 "oauth2" 的过滤器进行登录验证权限验证的资源
        filterMap.put("/sys/**", "oauth2");
        // 配置需要名为 "oauth2" 的过滤器进行权限验证的资源
//        filterMap.put("/sys/**", "oauth2,roles[admin]");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
